using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Shared.Enums;

namespace UniversalAdmin.WebApi.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
public class DocumentPermissionController : ControllerBase
{
    private readonly IDocumentPermissionService _documentPermissionService;
    private readonly IDocumentService _documentService;

    public DocumentPermissionController(
        IDocumentPermissionService documentPermissionService,
        IDocumentService documentService)
    {
        _documentPermissionService = documentPermissionService;
        _documentService = documentService;
    }

    [HttpPost]
    [Authorize]
    public async Task<IActionResult> CreatePermission([FromBody] CreateDocumentPermissionDto dto)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 检查是否为文档所有者或管理员
        var document = await _documentService.GetDocumentByIdAsync(dto.DocumentId);
        if (document == null)
        {
            return NotFound(new { message = "文档不存在" });
        }

        if (document.CreatedBy != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        try
        {
            var permission = await _documentPermissionService.CreatePermissionAsync(dto);
            return CreatedAtAction(nameof(GetPermissionById), new { id = permission.Id }, permission);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpDelete("{id}")]
    [Authorize]
    public async Task<IActionResult> DeletePermission(Guid id)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 检查是否为文档所有者或管理员
        var permission = await _documentPermissionService.GetPermissionByIdAsync(id);
        if (permission == null)
        {
            return NotFound();
        }

        var document = await _documentService.GetDocumentByIdAsync(permission.DocumentId);
        if (document == null)
        {
            return NotFound(new { message = "文档不存在" });
        }

        if (document.CreatedBy != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        var result = await _documentPermissionService.DeletePermissionAsync(id);
        if (!result)
        {
            return NotFound();
        }
        return NoContent();
    }

    [HttpPut("{id}")]
    [Authorize]
    public async Task<IActionResult> UpdatePermission(Guid id, [FromBody] UpdateDocumentPermissionDto dto)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 检查是否为文档所有者或管理员
        var permission = await _documentPermissionService.GetPermissionByIdAsync(id);
        if (permission == null)
        {
            return NotFound();
        }

        var document = await _documentService.GetDocumentByIdAsync(permission.DocumentId);
        if (document == null)
        {
            return NotFound(new { message = "文档不存在" });
        }

        if (document.CreatedBy != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        try
        {
            var result = await _documentPermissionService.UpdatePermissionAsync(id, dto);
            if (!result)
            {
                return NotFound();
            }
            return Ok(await _documentPermissionService.GetPermissionByIdAsync(id));
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("{id}")]
    [Authorize]
    public async Task<IActionResult> GetPermissionById(Guid id)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var permission = await _documentPermissionService.GetPermissionByIdAsync(id);
        if (permission == null)
        {
            return NotFound();
        }

        // 检查是否为文档所有者或管理员
        var document = await _documentService.GetDocumentByIdAsync(permission.DocumentId);
        if (document == null)
        {
            return NotFound(new { message = "文档不存在" });
        }

        if (document.CreatedBy != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        return Ok(permission);
    }

    [HttpGet("document/{documentId}")]
    [Authorize]
    public async Task<IActionResult> GetPermissionsByDocumentId(Guid documentId)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 检查是否为文档所有者或管理员
        var document = await _documentService.GetDocumentByIdAsync(documentId);
        if (document == null)
        {
            return NotFound(new { message = "文档不存在" });
        }

        if (document.CreatedBy != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        var permissions = await _documentPermissionService.GetPermissionsByDocumentIdAsync(documentId);
        return Ok(permissions);
    }

    [HttpGet("user/{userId}")]
    [Authorize(Roles = "Admin,SuperAdmin")]
    public async Task<IActionResult> GetPermissionsByUserId(Guid userId)
    {
        var permissions = await _documentPermissionService.GetPermissionsByUserIdAsync(userId);
        return Ok(permissions);
    }

    [HttpGet("role/{roleId}")]
    [Authorize(Roles = "Admin,SuperAdmin")]
    public async Task<IActionResult> GetPermissionsByRoleId(Guid roleId)
    {
        var permissions = await _documentPermissionService.GetPermissionsByRoleIdAsync(roleId);
        return Ok(permissions);
    }

    [HttpGet("check")]
    [Authorize]
    public async Task<IActionResult> CheckPermission(
        [FromQuery] Guid documentId,
        [FromQuery] PermissionType requiredPermission)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var hasPermission = await _documentPermissionService.CheckPermissionAsync(documentId, Guid.Parse(userId), requiredPermission);
        return Ok(new { hasPermission });
    }

    [HttpGet("accessible-documents")]
    [Authorize]
    public async Task<IActionResult> GetAccessibleDocuments([FromQuery] PermissionType requiredPermission)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var documentIds = await _documentPermissionService.GetAccessibleDocumentIdsAsync(Guid.Parse(userId), requiredPermission);
        return Ok(documentIds);
    }
}